import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Col, Form, Input, message, Row, Select, Spin, TreeSelect } from 'antd';
import { Ref, useContext, useEffect, useRef, useState } from 'react';
import { DesignModelAPI } from '../common/type';

import pageStyles from '@/common/pageLayout.less';
import { modelDeployService, treeloadMdicMapServuces } from '../services';
import { DesignManageContext } from '../mconfig';

export const PublishActivetiModal: React.FC<DesignModelAPI.IPublishActivitiModal> = ({ onClose, visible, checkRowObj }) => {
  /**
   * modal ref
   */
  const publishActivitiRef: Ref<IOneModalRef> = useRef(null);

  /**
   * 表单 form
   */
  const [publishForm] = Form.useForm();

  /**
   * 关闭弹窗
   */
  const onCloseModal = () => {
    if (publishActivitiRef) {
      if (publishActivitiRef.current) {
        if (publishActivitiRef.current.onModalCancel) {
          publishActivitiRef.current.onModalCancel();
        }
      }
    }
  };
  const {
    typeSelectRow,
    rightTableProps: { reloadTableData },
  } = useContext(DesignManageContext);

  /**
   * 是否显示流程类别
   */
  const [isFlowType, setIsFlowType] = useState<boolean>(false);

  /**
   * 保存流程数据
   */
  const [editFlowList, setEditFlowList] = useState<any[]>([]);

  /**
   * 处理异步数据
   * @param treeData 原有数据
   * @param parentKey 异步数据的 key
   * @param childList 异步的数据
   * @param selectKeys 异步数据的字段key
   */
  const handLoadDataList = (treeData: Record<string, any>[], parentKey: string, childList: Record<string, any>[], selectKeys: string) => {
    if (treeData?.length <= 0 || treeData == null || treeData == undefined) {
      return [];
    }
    treeData?.forEach((item, index) => {
      if (item?.[`${selectKeys}`] == parentKey) {
        treeData[index] = {
          ...item,
          children: childList,
        };
      }
    });
    return treeData;
  };

  /**
   * 获取异步数据回调
   * @param res
   */
  const treeloadMdicMapCallback = (res: any) => {
    if (res && res?.msgFlag) {
      let [parentKey]: string[] = Object.keys(res?.obj);
      let loadChildList: Record<string, any>[] = res?.obj?.[parentKey];
      let NewTreeData: Record<string, any>[] = handLoadDataList([typeSelectRow], parentKey, loadChildList, 'flowType');
      setEditFlowList(NewTreeData);
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 获取类别数据
   */
  const { treeLoadMdicMapLoading, treeLoadMdicMapRun } = treeloadMdicMapServuces(treeloadMdicMapCallback);

  useEffect(() => {
    if (checkRowObj && checkRowObj?.id) {
      publishForm?.setFieldsValue({
        ...checkRowObj,
        isDefault: '0',
        isChangeType: '0',
        deptFlag: '0',
      });
      // if (isFlowType) {
      //   treeLoadMdicMapRun(typeSelectRow?.flowType);
      // }
    }
  }, [checkRowObj, typeSelectRow]);

  /**
   * 处理树数据
   * @param data
   * @returns
   */
  const handleTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      return {
        ...item,
        title: item?.name,
        searchtitle: item?.name,
        key: item?.id,
        value: item?.id,
        children: item?.children && item?.children?.length > 0 ? handleTreeData(item?.children) : null,
        disabled: item?.tableName ? true : false,
      };
    });
  };

  /**
   * 发布流程接口回调
   * @param res
   */
  const modelDeployCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      onCloseModal();
      reloadTableData();
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入发布接口
   */
  const { modelDeployLoading, modelDeployRun } = modelDeployService(modelDeployCallback);

  /**
   * 发布流程
   */
  const onOkPublish = () => {
    publishForm?.validateFields()?.then((values: any) => {
      let publishObj = {
        ...values,
        orderType: checkRowObj?.orderType,
        id: checkRowObj?.id,
        keyWord: checkRowObj?.keyWord,
        versionNum: checkRowObj?.versionNum,
        isChangeType: '0',
        businessCategory: isFlowType ? values?.businessCategory : checkRowObj?.businessCategory,
        ownCompanyID: checkRowObj?.ownCompanyID, // 流程发布时，需要传这个字段-单位
      };
      modelDeployRun(publishObj);
    });
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={publishActivitiRef}
        title={'发布流程'}
        width={document.body.clientWidth * 0.3}
        onCancel={onClose}
        bodyStyle={{
          padding: '5px 0px',
        }}
        centered
        confirmLoading={treeLoadMdicMapLoading || modelDeployLoading}
        onOk={onOkPublish}
      >
        <Spin spinning={treeLoadMdicMapLoading || modelDeployLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form labelAlign="right" form={publishForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    name="name"
                    label="流程名称"
                    rules={[
                      {
                        required: true,
                        message: '请输入流程名称',
                      },
                    ]}
                  >
                    <Input allowClear placeholder="请输入流程名称" />
                  </Form.Item>
                </Col>
                {/* <Col span={24}>
                  <Form.Item
                    name="isChangeType"
                    label="更换类别"
                    initialValue={'0'}
                  >
                    <Select
                      onChange={(e: any) => {
                        if (e == '0') {
                          setIsFlowType(false);
                        }
                        if (e == '1') {
                          setIsFlowType(true);
                          treeLoadMdicMapRun(typeSelectRow?.flowType);
                        }
                      }}
                    >
                      <Select.Option value={'0'} key={'0'}>
                        否
                      </Select.Option>
                      <Select.Option value={'1'} key={'1'}>
                        是
                      </Select.Option>
                    </Select>
                  </Form.Item>
                </Col> */}
                {/* {isFlowType && (
                  <Col span={24}>
                    <Form.Item name="businessCategory" label="流程类别">
                      <TreeSelect
                        showSearch
                        treeNodeFilterProp={'searchtitle'}
                        placeholder="请选择流程类别"
                        treeData={handleTreeData(editFlowList)}
                      />
                    </Form.Item>
                  </Col>
                )} */}

                <Col span={24}>
                  <Form.Item name="isDefault" label="是否默认" initialValue={'0'}>
                    <Select>
                      <Select.Option value={'0'} key={'0'}>
                        否
                      </Select.Option>
                      <Select.Option value={'1'} key={'1'}>
                        是
                      </Select.Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item name="deptFlag" label="是否科研机构" initialValue={'0'}>
                    <Select>
                      <Select.Option value={'0'} key={'0'}>
                        否
                      </Select.Option>
                      <Select.Option value={'1'} key={'1'}>
                        是
                      </Select.Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
